#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>


struct arg
{
  int * T;
  int d;
  int f;
  int somme;
};


int *init_table(int t)
{
  srand(time(NULL));
  int i;
  int * Tab = malloc(sizeof(int)*t);
  for (i=0 ; i<t ; i++)
    {
      Tab[i] = rand()%100;
    }
  return Tab;
}


void * divide(void * A)
{
  struct arg * B = (struct arg *) A;
  if (B->d==B->f)
    {
      B->somme = B->T[B->d];
      return B;
    }
  else
    {
      struct arg * A1= malloc(sizeof(struct arg));
      A1->T = B->T;
      A1->d = B->d;
      A1->f = (B->d+B->f)/2;

      struct arg * A2 = malloc(sizeof(struct arg));;
      A2->T = B->T;
      A2->d = (B->d+B->f)/2+1;
      A2->f = B->f;
      
      pthread_t threadA1;
      int * retA1;
      struct arg * Ar1;
      pthread_create(&threadA1,NULL,divide,A1);
      pthread_join(threadA1,&Ar1);
     
      pthread_t threadA2;
      int * retA2;
      struct arg * Ar2;
      pthread_create(&threadA2,NULL,divide,A2);
      pthread_join(threadA2,&Ar2);
      
      B->somme = Ar2->somme + Ar1->somme;
      free(A1);
      free(A2);
      return B;
    }
}

int main(int argc, char* argv[])
{
  int i;
  struct arg * res;
  if(argc!=2)
  {
  	printf("entrez la taille en argument");
  	return 0;
  }
  
  
  int taille = atoi(argv[1]);
  int * T = init_table(taille);
  /*printf("Tableau :\n");
  for (i=0;i<taille;i++)
    {
      printf("%d  ",T[i]);
    }
  */
  //initialisation des arguments
  struct arg * A =  malloc(sizeof(struct arg));
  A->T=T;
  A->d=0;
  A->f=taille-1;

  double debut,fin;
  debut = clock();
  pthread_t thread1;
  pthread_create(&thread1,NULL,divide,A);
  pthread_join(thread1,&res);
  fin = clock();
  printf("%d ",taille);
  free(A);
  free(T);
  fprintf(stdout,"%f\n",(double) (fin-debut)/(double)CLOCKS_PER_SEC);
  return 1;
}
